<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller;

use buwang\base\AdminBaseController;
use think\facade\Filesystem;
use app\manage\model\ConfigGroup;
use app\manage\model\ConfigGroupData;
use app\common\model\Miniapp;
use app\manage\model\admin\Plugin;

class Group extends AdminBaseController
{
    public function index()
    {
        $miniapp = Miniapp::select()->toArray();
        $plugin = Plugin::select()->toArray();
        return view('', ['miniapp' => $miniapp, 'plugin' => $plugin]);
    }

    /**
     * 配置分类列表
     *
     * @return \think\Response
     */
    public function getconfiglist()
    {
        //搜索条件
        $map = array();
        $sort = 'a.id desc';
        //页数
        $page = input('page/d', 1);
        //条数
        $limit = input('limit/d', 10);
        $id = input('id/d', 0);
        $name = input('name/s', '');
        $config_name = input('config_name/s', '');
        $scopes = input('scopes/s', '');
        $dir = input('dir/s', '');
        $plugin_name = input('plugin_name/s', '');//插件

        if ($dir) {
            $map[] = ['a.dir', '=', $dir];
        }
        if ($scopes) {
            $map[] = ['a.scopes', '=', $scopes];
        }
        if ($id) {
            $map[] = ['a.id', '=', $id];
        }
        if ($plugin_name != null) {
            $map[] = ['a.plugin_name', '=', $plugin_name];
        }

        if ($name) {
            $map[] = ['a.name', 'like', $name . '%'];
        }
        if ($config_name) {
            $map[] = ['a.config_name', 'like', $config_name . '%'];
        }
        $list = ConfigGroup::valiWhere('a', null, $dir)
            ->join('miniapp m', 'm.dir = a.dir', 'left')
            ->field(['a.*', 'm.title as miniapp_name'])
            ->where($map)
            ->page($page, $limit)
            ->order($sort)
            ->select();
        //处理value字段
//        foreach ($list as $v){
//            if($v['fields']){
//                $temp = json_decode($v['fields'], true)[0];
//                $v['data_field'][] =[
//                    'label'=>$temp
//                ];
//            }
//        }
        $count = ConfigGroup::valiWhere('a', null, $dir)
            ->join('miniapp m', 'm.dir = a.dir', 'left')
            ->where($map)
            ->count();
        //列表数据
        if (request()->param('return_type') == "old_json") {
            return json([
                'code' => 0,
                'msg' => 'success',
                'count' => $count,
                'data' => $list,
            ]);
        }
        return $this->success('success', ['total' => $count, 'list' => $list]);
    }

    /**
     * 添加组合数据分类
     * @return \think\Response|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (!isset($param['dir'])) $param['dir'] = '';

            $fields = array();
            $unique_array = array();
            foreach ($param['fields'] as $field) {
                if (is_array($field)) {
                    $rs = $field;
                } else {
                    $rs = json_decode(htmlspecialchars_decode($field), true);
                }

                if ($rs) {
                    $unique_array[] = $rs['config_name'];
                    $fields[] = $rs;
                }
            }
            ///判断是否有重复字段
            if (count($unique_array) != count(array_unique($unique_array))) {
                return $this->error('添加的字段中存在同名字段，请检查您的字段，去除同名字段！');
            }
            $param['fields'] = str_replace("\\\\", "\\", json_encode($fields, JSON_UNESCAPED_UNICODE));//数组转json$fields;
            //判断是否存在唯一标识
            $count = ConfigGroup::valiWhere('', null, $param['dir'])->where('config_name', $param['config_name'])->where('dir', $param['dir'])->count();
            if ($count) return $this->error('该字段已存在');
            $result = ConfigGroup::valiWhere('', null, $param['dir'])->save($param);
            if ($result) {
                return $this->success('添加分组成功');
            } else {
                return $this->error('添加失败');
            }
        }

        $miniapp = Miniapp::select()->toArray();
        $plugin = Plugin::select()->toArray();
        if ($this->request->isAjax()) {
            return $this->success("获取成功", ['entity' => null, 'fields' => [], 'miniapp' => $miniapp, 'plugin' => $plugin]);
        } else {
            return view('edit', ['entity' => null, 'fields' => [], 'miniapp' => $miniapp, 'plugin' => $plugin]);
        }

    }


    public function edit()
    {
        $app = input('app/s', '');
        if ($this->request->isPost()) {
            $param = $this->request->only(['dir','config_name','desc','fields','id','miniapp_name','name','plugin_name','scopes']);
            if (!isset($param['dir'])) $param['dir'] = '';

            $fields = array();
            $unique_array = array();
            foreach ($param['fields'] as $field) {
                if (is_array($field)) {
                    $rs = $field;
                } else {
                    $rs = json_decode(htmlspecialchars_decode($field), true);
                }

                if ($rs) {
                    //如果是富文本则解析富文本数据
                    $unique_array[] = $rs['config_name'];
                    $fields[] = $rs;

                }
            }
            ///判断是否有重复字段
            if (count($unique_array) != count(array_unique($unique_array))) {
                return $this->error('添加的字段中存在同名字段，请检查您的字段，去除同名字段！');
            }
            $param['fields'] = str_replace("\\\\", "\\", json_encode($fields, JSON_UNESCAPED_UNICODE));//数组转json$fields;
            //判断是否存在唯一标识
            $count = ConfigGroup::valiWhere('', null, $param['dir'])->where('config_name', $param['config_name'])->where('dir', $param['dir'])->where('id', '<>', $param['id'])->count();
            if ($count) return $this->error('该字段已存在');
            $result = ConfigGroup::valiWhere('', null, $param['dir'])->update($param);
            if ($result) {
                return $this->success('更新成功');
            } else {
                return $this->error('操作失败');
            }
        }else{
            $id = $this->request->get('id');
            $data = ConfigGroup::valiWhere('', null, $app)->find($id);
            $fields = array();
            if ($data) {
                $fieldsdata = $data['fields'];
                if ($fieldsdata) {
                    $fieldsdata = json_decode($fieldsdata, true);//json串传数组
                    if ($fieldsdata) $fields = $fieldsdata;
                    foreach ($fields as &$field) {
                        if ($field) {
                            $field['json'] = str_replace("\\\\", "\\", json_encode($field, JSON_UNESCAPED_UNICODE));
                            $field['type_name'] = ConfigGroup::getTypeName($field['type']);
                        }
                    }
                }

            }
            $miniapp = Miniapp::select()->toArray();
            $plugin = Plugin::select()->toArray();
            return view('', ['entity' => $data, 'fields' => $fields, 'miniapp' => $miniapp, 'plugin' => $plugin]);
        }
    }


    public function addconfig()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            unset($param['radio_value']);
            unset($param['checkbox_value']);
            unset($param['select_value']);
            if (in_array($param['config_name'], ['sort', 'status'])) return $this->error('字段[sort],[status]属于组合数据字段，请换个字段名');
            $param['id'] = uniqid();
            return $this->success('操作成功', $param);
        }
        //得到配置
        $tab_id = $this->request->get('tab_id');
        //查询所有分类
        $tab = [];
        //var_dump($tab);die;
        return view('editconfig', ['entity' => null, 'tab' => $tab, 'tab_id' => $tab_id]);
    }

    public function editconfig()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            unset($param['radio_value']);
            unset($param['checkbox_value']);
            unset($param['select_value']);
            if (in_array($param['config_name'], ['sort', 'status'])) return $this->error('字段[sort],[status]属于组合数据字段，请换个字段名');
            return $this->success('操作成功', $param);
        }
        $data = $this->request->get('data');
        if ($data) {
            $data = json_decode(str_replace("\\\\", "\\", htmlspecialchars_decode($data)), true);
            //如果是富文本则解析富文本数据
            if ($data['type'] == "r_textarea") {
                $r_textarea = base64_decode($data['value']);
                $data['value'] = urldecode($r_textarea);
            }
            unset($data['radio_value']);
            unset($data['checkbox_value']);
            unset($data['select_value']);
            $data['value'] = str_replace("__JING_HAO__", "#", $data['value']);
        } else {
            $data = [];
        }
        $tab_id = $this->request->get('tab_id');
        //查询所有分类
        $tab = [];
        return view('editconfig', ['entity' => $data, 'tab' => $tab, 'tab_id' => $tab_id]);
    }


    /**
     * 删除/批量删除
     * @return \think\Response
     */
    public function configsoftdleting()
    {
        $app = input('app/s', '');
        $ids = input('ids/s');
        $ids_array = explode(',', $ids);
        $list = array();
        foreach ($ids_array as $key) {
            $res = ConfigGroupData::valiWhere('', null, $app)->where('dir', $app)->where('group_id', $key)->find();
            if ($res) return $this->error('操作失败,该组合分类下存在未删除的数据');
            ConfigGroup::valiWhere('', null, $app)->where('id', $key)->delete();
        }
        return $this->success('删除成功');
    }


}